//
//  GCDTimer.m
//  bkshell
//
//  Created by nsm on 2018/3/30.
//  Copyright © 2018年 prin. All rights reserved.
//

#import "GCDTimer.h"

@interface GCDTimer ()
@property (nonatomic) BOOL isRun;
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation GCDTimer

- (GCDTimer *(^)(dispatch_queue_t))queue {
    @nsm_weak(self)
    return ^(dispatch_queue_t queue){
        @nsm_strong(self)
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        return self;
    };
}

- (GCDTimer *(^)(NSTimeInterval, NSTimeInterval))parameters {
    @nsm_weak(self)
    return ^(NSTimeInterval delay, NSTimeInterval interval){
        @nsm_strong(self)
        dispatch_source_set_timer(self.timer,
                                  dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
                                  interval * NSEC_PER_SEC,
                                  0);
        
        return self;
    };
}

- (GCDTimer *(^)(void (^)(void)))eventHandler {
    @nsm_weak(self)
    return ^(void(^eventHandler)(void)) {
        @nsm_strong(self)
        dispatch_source_set_event_handler(self.timer, eventHandler);
        return self;
    };
}

- (GCDTimer *(^)(void))resume {
    @nsm_weak(self)
    return ^{
        @nsm_strong(self)
        [self resumeTimer];
        return self;
    };
}

- (GCDTimer *(^)(void))pause {
    @nsm_weak(self)
    return ^{
        @nsm_strong(self)
        [self pauseTimer];
        return self;
    };
}

- (GCDTimer *(^)(void))cancel {
    @nsm_weak(self)
    return ^{
        @nsm_strong(self)
        [self cancelTimer];
        return self;
    };
}

#pragma mark - 事件
- (void)resumeTimer {
    if (_timer && !_isRun) {
        _isRun = YES;
        dispatch_resume(_timer);
    }
}

- (void)pauseTimer {
    if (_timer && _isRun) {
        _isRun = NO;
        dispatch_suspend(_timer);
    }
}

- (void)cancelTimer {
    if (_timer) dispatch_source_cancel(_timer);
}

- (void)stopTimer {
    if (_timer) {
        if (!_isRun) dispatch_resume(_timer);
        
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)dealloc {
    [self stopTimer];
}

@end
